<template>
  <a-modal
    :title="title"
    :width="1680"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :bodyStyle="{fullScreen: true}"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    okText="保存"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" v-bind="layout" :model="model" :rules="validatorRules">
        <a-row>
          <a-col span="8">
            <a-form-model-item label="处方名称" required prop="prescriptionName" :labelCol="{span: 6}"
                               :wrapperCol="{span: 18}">
              <a-input placeholder="请输入处方名称" v-model="model.prescriptionName" style="width: 80%;" />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item label="处方分类" :labelCol="{span: 4}" :wrapperCol="{span: 17}">
              <a-select placeholder="" v-model="model.categoryCode">
                <a-select-option value="">请选择</a-select-option>
                <a-select-option v-for="item in serviceList" :key="item.key" :value="item.key">{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item label="来源" :labelCol="{span: 4}" :wrapperCol="{span: 17}">
              <a-input placeholder="不填写，默认是本人" v-model="model.source" style="width: 80%;" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row justify="start">
          <a-form-model-item label="功能" required prop="functions" :labelCol="{span: 2}" :wrapperCol="{span: 20}">
            <a-input placeholder="请输入功能或作用" v-model="model.functions" />
          </a-form-model-item>
        </a-row>
        <a-row justify="start">
          <a-form-model-item label="主治" required prop="indications" :labelCol="{span: 2}" :wrapperCol="{span: 20}">
            <a-input placeholder="请输入主治" v-model="model.indications" />
          </a-form-model-item>
        </a-row>
        <a-row justify="start">
          <a-form-model-item label="加减(备住)" :labelCol="{span: 2}" :wrapperCol="{span: 20}">
            <a-textarea row="3" placeholder="请输入加减" v-model="model.remark" />
          </a-form-model-item>
        </a-row>


      </a-form-model>
      <a-divider orientation="left">

      </a-divider>

      <a-card style="border-radius: 10px;width: 100%">
        中药处方
        <a-select v-model="model.attrType" defaultValue="饮片" style="margin-left: 4px;width: 120px">
          <a-select-option value="饮片">饮片</a-select-option>
          <a-select-option value="颗粒">颗粒</a-select-option>
        </a-select>
        <label>{{ totalDose }}</label>
        <a-divider />
        <a-row>
          <a-col v-for="data in dataSource" span="3">
            <label style="font-weight : bold">{{ data.medicineName }}</label>
            <a-input-number v-model="data.dose" placeholder="用量" style="width: 80px;margin-left: 4px" />
            <label style="margin-left: 3px;font-weight : bold">{{ data.unit }}</label>
          </a-col>
        </a-row>

        <a-row style="margin-top: 30px">
          <a-input-number v-model="model.doseQty" placeholder="剂量" style="width: 80px;" />
          <label style="margin-left: 4px;font-weight : bold">剂</label>

          <j-dict-select-tag
            style="width: 130px;margin-left: 6px;"
            placeholder="请选择给药途径"
            dictCode="drug_delivery_route2"
            v-model="model.usages" />

          <!--频次-->
          <j-dict-select-tag
            style="width: 120px;margin-left: 6px;"
            placeholder="请选择服用剂数"
            dictCode="daily_dose"
            v-model="model.dailyDose" />

          <j-dict-select-tag
            style="width: 120px;margin-left: 6px;"
            placeholder="请选择服用频次"
            dictCode="use_frequency"
            v-model="model.frequency" />

          <j-dict-select-tag
            style="width: 120px;margin-left: 6px;"
            placeholder="每次用量"
            dictCode="dosage_taken"
            v-model="model.dose" />
        </a-row>
      </a-card>

      <a-popover title="" placement="bottom" trigger="click">
        <template slot="content">
          <a-table
            ref="table"
            size="middle"
            bordered
            :scroll="{ x: 500,y: 200}"
            rowKey="id"
            :columns="columnsMedicine"
            :dataSource="medicineDataSource"
            :customRow="onClickRow"
            style="margin-top: 10px" />
        </template>
        <a-auto-complete
          v-model="value"
          :data-source="dataSource"
          style="width: 500px;margin-top: 10px"
          placeholder="输入药品名称或拼音码"
          @search="onSearch"
        >
          <a-input>
            <a-icon slot="prefix" type="search" class="certain-category-icon" />
          </a-input>
        </a-auto-complete>
      </a-popover>

    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction, putAction, getAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'hHisPrescriptionTemplateModal',
  data() {
    return {
      title: '中药处方模板',
      visible: false,
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 }
      },
      confirmLoading: false,
      validatorRules: {
        prescriptionName: [{ required: true, message: '请输入处方名称!' }],
        functions: [{ required: true, message: '请输入功能或作用!' }],
        indications: [{ required: true, message: '请输入主治!' }]
      },
      url: {
        add: '/his/prescription/template/chinese/medicine',
        edit: '/his/prescription/template/chinese/medicine',
        getDetail: '/his/prescription/template/detail/',
        selectList: '/his/prescription/template/category/selectList'
      },
      value: '',
      disableMixinCreated: true,
      medicineDataSource: [],
      columnsMedicine: [
        {
          title: '药品名称',
          align: 'center',
          dataIndex: 'medicineName',
          width: 200
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'standard',
          width: 150
        },
        {
          title: '厂商',
          align: 'center',
          dataIndex: 'factoryName',
          width: 160
        },
        {
          title: '价格',
          align: 'center',
          dataIndex: 'salePrice',
          width: 130
        },
        {
          title: '库存',
          align: 'center',
          dataIndex: 'stock',
          width: 120
        }

      ],
      dataSource: [],

      model: {
        usages: '',//中药用法
        frequency: '',//中药频次
        dose: '',//中药每次用量
        qty: '',//共多少剂中药
        doseQty:'',//一天服用多少剂中药
      },
      totalDose: '',
      serviceList: []
    }
  },
  created() {
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.loadDataMedicine()
  },
  methods: {
    onSearch(searchText) {
      this.loadDataMedicine(searchText)
    },
    loadDataMedicine(medicineName) {
      getAction('/his/warehousing/medicine/list', { 'medicineName': medicineName }).then((res) => {
        if (res.success) {
          this.medicineDataSource = res.result.records || res.result
        } else {

        }
      }).finally(() => {

      })
    },
    onClickRow(record) {
      const that = this
      return {
        on: {
          click: () => {
            for (const d in that.dataSource) {
              if (d['medicineId'] == record.id) {
                return
              }
            }
            that.dataSource.push({
              'medicineId': record.id,
              'medicineName': record.medicineName,
              'standard': record.standard,
              'unit': record.conversionUnit,
              'dose': '1'
            })
            that.totalDose = that.dataSource.length + ' 味，单剂' + that.dataSource[0].unit
          }
        }
      }
    },
    calTotalDose(index) {
      const data = this.dataSource[index]
      const result = (data['dose'] * 1) * (data['day'] * 1)
      this.dataSource[index].totalDose = result
    },
    deleteRow(index) {
      const that = this
      that.dataSource.splice(index, 1)
    },

    add(record) {
      this.model = Object.assign({}, this.modelDefault)
      this.model.categoryCode=record.code;
      this.visible = true
      getAction(this.url.selectList).then((res) => {
        if (res.success) {
          this.serviceList = res.result
        }
      })
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      getAction(this.url.selectList).then((res) => {
        if (res.success) {
          this.serviceList = res.result
        }
      })
      getAction(this.url.getDetail + '/' + record.prescriptionCode).then((res) => {
        if (res.success) {
          this.dataSource = res.result
        }
      })
    },
    close() {
      this.$refs.form.clearValidate()
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          this.model.templateType = '4'
          this.model.items = this.dataSource
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    }

  }
}
</script>

<style scoped>
.card {
  border: 1px solid rgba(0, 0, 0, 0.65);
  border-radius: 10px;
  margin-bottom: 20px;
}

.card-title {
  color: #333; /* 设置标题颜色 */
  font-size: 18px;
  margin-bottom: 10px;
}
</style>